import { APIGoodsDetail, APIAddCart } from "./fetch.js";
import { queryString, getCookie } from './tools.js';

$('#head').load('../../layout/head.html');
$('#footer').load('../../layout/footer.html');

layui.use(['layer'], function () {

  var gid = queryString('gid');

  APIGoodsDetail({
    gid
  }).then(({ data:{gname,desc,price,imgs,detail} }) => {
    var html = '';
    $('.right_1_3').html(gname);
    $('.sp2').html(price);

    $.each(JSON.parse(imgs),function(index,item){
      if(index == 0) $('.list-left .top img').attr('src',item);
      html += `
      <div class="bottom"><img src="${item}" alt="" class="botImg"></div>`
    })

    $('.bottom_1').html(html);

    $('.list-bottom').html(detail);
  })

  $(document).on('mouseover', '.bottom img', function () {
    $('.list-left .top img').attr('src', $(this).attr('src'));
})

  $(document).on('click', '.right_3_5', function() {
    var username = getCookie('login_user');
    if(!username) {
      sessionStorage.loginBack = location.href;
      location.href = '../../html/login.html';
    }

    APIAddCart({
      gid,
      username,
      img: $('.list-left .top img').attr('src'),
      gname: $('.right_1_3').html(),
      price: $('.sp2').html(),
      count: $('.right_3_2').html()
    }).then(({code, msg}) => {
      if(code) {
        location.href = '../../html/cart.html'
        layer.msg(msg)
      } else {
        layer.msg(msg)
      }
    })


  })


})